"""
pytest配置文件

提供测试夹具和配置。
"""

import pytest
import tempfile
import os
from pathlib import Path
from unittest.mock import Mock, MagicMock


@pytest.fixture
def temp_dir():
    """临时目录夹具"""
    with tempfile.TemporaryDirectory() as tmpdir:
        yield Path(tmpdir)


@pytest.fixture
def mock_es_client():
    """模拟ES客户端"""
    client = Mock()
    
    # 模拟基本方法
    client.index_exists.return_value = True
    client.get_mapping.return_value = {
        'test_index': {
            'mappings': {
                'properties': {
                    '@timestamp': {'type': 'date'},
                    'message': {'type': 'text'}
                }
            }
        }
    }
    client.get_settings.return_value = {
        'test_index': {
            'settings': {
                'index': {
                    'number_of_shards': '1',
                    'number_of_replicas': '0'
                }
            }
        }
    }
    client.create_index.return_value = True
    client.bulk.return_value = {'errors': False, 'items': []}
    client.search.return_value = {
        'hits': {
            'total': {'value': 0},
            'hits': []
        }
    }
    client.scroll.return_value = {
        'hits': {'hits': []}
    }
    client.get_cluster_info.return_value = {
        'cluster_name': 'test-cluster',
        'nodes': {}
    }
    
    return client


@pytest.fixture
def sample_documents():
    """示例文档数据"""
    return [
        {
            '_id': '1',
            '_source': {
                '@timestamp': '2023-01-01T00:00:00Z',
                'message': 'Test message 1',
                'level': 'INFO'
            }
        },
        {
            '_id': '2',
            '_source': {
                '@timestamp': '2023-01-01T01:00:00Z',
                'message': 'Test message 2',
                'level': 'ERROR'
            }
        },
        {
            '_id': '3',
            '_source': {
                '@timestamp': '2023-01-01T02:00:00Z',
                'message': 'Test message 3',
                'level': 'WARNING'
            }
        }
    ]


@pytest.fixture
def sample_mapping():
    """示例索引映射"""
    return {
        'test_index': {
            'mappings': {
                'properties': {
                    '@timestamp': {
                        'type': 'date',
                        'format': 'strict_date_optional_time||epoch_millis'
                    },
                    'message': {
                        'type': 'text',
                        'analyzer': 'standard'
                    },
                    'level': {
                        'type': 'keyword'
                    },
                    'user': {
                        'type': 'object',
                        'properties': {
                            'name': {'type': 'keyword'},
                            'age': {'type': 'integer'}
                        }
                    },
                    'tags': {
                        'type': 'keyword'
                    },
                    'count': {
                        'type': 'long'
                    },
                    'score': {
                        'type': 'float'
                    }
                }
            }
        }
    }


@pytest.fixture
def mock_backup_metadata():
    """模拟备份元数据"""
    from datetime import datetime, timezone
    
    return {
        'backup_id': 'test_backup_123',
        'source_index': 'test_index',
        'backup_path': '/tmp/test_backup',
        'start_time': datetime(2023, 1, 1, tzinfo=timezone.utc),
        'end_time': datetime(2023, 1, 1, 1, tzinfo=timezone.utc),
        'status': 'completed',
        'total_documents': 1000,
        'backed_up_documents': 1000,
        'total_size_bytes': 1024000,
        'compressed_size_bytes': 512000,
        'chunks': [
            '/tmp/test_backup/chunk_000001.json.gz',
            '/tmp/test_backup/chunk_000002.json.gz'
        ],
        'strategy': {
            'strategy_type': 'full',
            'batch_size': 1000,
            'compression': 'gzip'
        }
    }


@pytest.fixture
def mock_config():
    """模拟配置"""
    return {
        'elasticsearch': {
            'hosts': ['localhost:9200'],
            'username': 'elastic',
            'password': 'password',
            'timeout': 60
        },
        'backup': {
            'default_strategy': 'full',
            'batch_size': 1000,
            'compression': 'gzip',
            'parallel_workers': 4,
            'validate_data': True
        },
        'storage': {
            'root_path': '/tmp/es-archive',
            'max_storage_size': '10GB',
            'retention_days': 30
        },
        'monitoring': {
            'enable_metrics': True,
            'collection_interval': 5.0
        }
    }


def pytest_configure(config):
    """pytest配置"""
    # 添加自定义标记
    config.addinivalue_line(
        "markers", "integration: mark test as integration test"
    )
    config.addinivalue_line(
        "markers", "performance: mark test as performance test"
    )
    config.addinivalue_line(
        "markers", "slow: mark test as slow running"
    )


def pytest_collection_modifyitems(config, items):
    """修改测试收集"""
    # 为集成测试添加跳过标记（除非明确运行）
    if not config.getoption("--run-integration"):
        skip_integration = pytest.mark.skip(reason="需要 --run-integration 选项运行集成测试")
        for item in items:
            if "integration" in item.keywords:
                item.add_marker(skip_integration)


def pytest_addoption(parser):
    """添加命令行选项"""
    parser.addoption(
        "--run-integration",
        action="store_true",
        default=False,
        help="运行集成测试"
    )
    parser.addoption(
        "--run-performance",
        action="store_true", 
        default=False,
        help="运行性能测试"
    )
